//
//  WebViewController.m
//  iLiteNote
//
//  Created by xiangism on 15/8/31.
//  Copyright (c) 2015年 LiteNice. All rights reserved.
//

#import "WebViewController.h"
#import "TextViewController.h"
#import "SlideMenuView.h"
#import "AppUtility.h"
#import "InputCryptKeyController.h"
#import "MkNode.h"
#import "GitInfo.h"
#import "NSString+NotePath.h"

@interface WebViewController () {
    UIWebView *_webView;
}

@end


@implementation WebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    UINavigationItem *navItem = self.navigationItem;
    UIBarButtonItem *leftBtn = [[UIBarButtonItem alloc] initWithTitle:@"目录" style:UIBarButtonItemStylePlain target:self action:@selector(leftTouch:)];
    UIBarButtonItem *rightBtn = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:@selector(editTouch:)];
    
    navItem.leftBarButtonItem = leftBtn;
    navItem.rightBarButtonItem = rightBtn;
    
    _webView = [[UIWebView alloc] initWithFrame:self.view.frame];
    [self.view addSubview:_webView];
    [self setWebViewText:@"blank"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
- (IBAction)leftTouch:(id)sender {
    if (self.slideMenu) {
        [self.slideMenu toggleShowMenu];
    }
}

- (void) navigateFile:(NSString*)notePath {
    self.notePath = notePath;
    
    GitInfo *info = [GitInfo shareGitInfo];
    NSString *rootPath = [info getGitPath];
    NSRange range = [self.notePath rangeOfString:rootPath];
    
    UINavigationItem *navItem = self.navigationItem;
    
    if (range.length > 0) {
        NSString *sub = [self.notePath substringFromIndex:range.length+1];
        NSMutableArray *path = [NSMutableArray arrayWithArray:[sub componentsSeparatedByString:@"/"]];
        
        for (int i = 0; i < path.count-1; ++i) {
            path[i] = [path[i] substringWithRange:NSMakeRange(0, 1)];
        }
        NSRange r2 = [path[path.count-1] rangeOfString:@"." options:NSBackwardsSearch];
        path[path.count-1] = [path[path.count-1] substringWithRange:NSMakeRange(0, r2.location)];
        NSString * title = [path componentsJoinedByString:@"/"];
        navItem.title = title;
        
    } else {
        navItem.title = @"无文件名";
    }
    
    [self refreshWebView];
}

- (void) scrollAnchor:(NSString*)anchor {
    NSString *r = [_webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"window.location.hash='%@'", anchor]];
    NSLog(@"eval Js:%@", r);
    //doc
    //http://iphonedevsdk.com/forum/iphone-sdk-development/2435-navigating-to-named-anchor-on-uiwebview.html 
    //下面这句不起作用
    //NSString *r = [_webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"var anchor = document.getElementById(\"%@\");window.scarollTo(anchor.offsetLeft, anchor.offsetTop);", anchor]];
}

- (void)inputCrypt:(NSString*)notePath {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"输入密码" message:[notePath getBaseName] preferredStyle:UIAlertControllerStyleAlert];
    [alert addTextFieldWithConfigurationHandler:^(UITextField *field) {
        field.secureTextEntry = YES;
        field.placeholder = @"vim密码";
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        
    }];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        UITextField *txt = alert.textFields.firstObject;
        TextViewController *txtVc = [[TextViewController alloc] init:notePath];
        txtVc.cryptKey = txt.text;
        [self.navigationController pushViewController:txtVc animated:YES];
    }];
    [alert addAction:cancelAction];
    [alert addAction:okAction];
    [self presentViewController:alert animated:YES completion:nil];
}

- (IBAction)editTouch:(id)sender {
    if ([AppUtility isCryptFileWithFileName:self.notePath]) {
        //InputCryptKeyController *cryptVc = [[InputCryptKeyController alloc] initWithPath:self.notePath withWeb:self];
        //[self.navigationController pushViewController:cryptVc animated:YES];
        [self inputCrypt:self.notePath];
        
    } else {
        TextViewController *txtVc = [[TextViewController alloc]init:self.notePath];
        txtVc.refreshBlock = ^{
            [self refreshWebView];
        };
        [self.navigationController pushViewController:txtVc animated:YES];
    }
}

- (void)refreshWebView 
{
    if (!self.notePath) {
        return;
    }
    if ([AppUtility isCryptFileWithFileName:self.notePath]) {
        NSString *str = [NSString stringWithFormat: @"%@ Vim Crypt", [self.notePath getBaseName]];
        [self setWebViewText:str];
    } else {
        [NSThread detachNewThreadSelector:@selector(markdownWork:) toTarget:self withObject:@{@"notepath":self.notePath}];
    }
    
    //NSURL *url = [[NSURL alloc]initWithString:@"http://m.baidu.com"];
    //[_webView loadRequest:[NSURLRequest requestWithURL:url]];
}

- (void)setWebViewText:(NSString*)text
{
    NSString *css_text = @"<html>"
    "<head>"
    "    <meta http-equiv=\"content-type\" content=\"text/html;charset=UTF-8\">"
    "    <style type=\"text/css\">"
    "        body { color: #444444; font-size:%dpt; line-height:1.5; word-wrap: break-word; font-family: DejaVu Sans Mono, \\5FAE\\8F6F\\96C5\\9ED1; }"
    "    </style>"
    "</head>"
    "<body><p/>"
    "%@"
    "</body></html>" ;
    
    NSString *html = [NSString stringWithFormat:css_text, 20, text];
    [_webView loadHTMLString:html baseURL:nil];
    _webView.scalesPageToFit = YES;
}

- (void)markdownWork:(NSDictionary*)dict
{
    @autoreleasepool {
        NSString *path = dict[@"notepath"];
        
        NSDate *t1 = [NSDate date];
        NSString *text = [[NSString alloc]initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
        NSArray *ss = [text componentsSeparatedByString:@"\n"];
        
        unsigned long count = [ss count];
        
        NSString * dir_file = path.stringByDeletingLastPathComponent;
        
        std::vector<std::string> lines;
        for (int i = 0; i < count; ++i) {
            NSString *s = ss[i];
            
            const char *p = [s cStringUsingEncoding:NSUTF8StringEncoding];
            lines.push_back(std::string(p));
        }
        
        int font_size = 25;
        if ([AppUtility isIPad]) {
            font_size = 18;
        }
        std::pair<std::string, AnchorNode*> p = SyntaxMk(lines, [dir_file cStringUsingEncoding:NSUTF8StringEncoding], font_size);
        NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingUTF8);
        NSString *md = [[NSString alloc]initWithBytes:p.first.c_str() length:p.first.size() encoding:enc];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (path == self.notePath) {
                [_webView loadHTMLString:md baseURL:nil];
                _webView.scalesPageToFit = YES;
                
                /*NSString *save_path = [NSString stringWithFormat:@"%@/Documents/save.html", NSHomeDirectory()];
                NSLog(@"path: %@", save_path);
                NSData *data = [md dataUsingEncoding:enc];
                [data writeToFile:save_path atomically:NO];*/
            }
        });
        
        
        ReleaseAnchorNode(p.second);
        NSDate *t2 = [NSDate date];
        double second = [t2 timeIntervalSince1970] - [t1 timeIntervalSince1970];
        printf("time: %0.4f\n", second);
    }
}

- (void) leftMenuHandle:(BOOL)isShow
{
    //如果在showLeftMenu时禁用userInteractionEnabled，则不要查看文本内容
    //如果不禁用，则不能点一下就收起menu
    _webView.userInteractionEnabled = !isShow;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
